package ophiux.wechat.template.base;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import com.alibaba.fastjson.JSONObject;

import ophiux.wechat.template.util.HttpUtil;

public class TokenUtil {
	/**  默认过期时间   7200秒*/
	private static long EXPIRE_TIME = 7100 * 1000;
	static Map<String,CacheObject> map = new ConcurrentHashMap<String,CacheObject>();
	
	public synchronized static String getToken(String appid,String appsecret) throws Exception {
		CacheObject cache = map.get("access_token");
		if(cache != null) {
//			log.info("access_token对象不为空，从缓存中取值");
			if(System.currentTimeMillis()>cache.getEXPIRE_TIME()) {
//				log.info("access_token当前时间大于有效时间，重新获取值");
				cache = getTokenValue(appid,appsecret);
				return cache.getCACHE_VALUE();
			}
//			log.info("access_token返回值：{}",JsonUtils.toJson(cache));
			return cache.getCACHE_VALUE();
		}
		cache = getTokenValue(appid,appsecret);
		return cache.getCACHE_VALUE();
	}
	
	public static CacheObject getTokenValue(String appid,String appsecret) throws Exception {
		CacheObject cache = new CacheObject();
//		String access_token = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret);
		String access_token = HttpUtil.httpsRequest("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appsecret, "GET", "", 3000);
//		log.info("微信返回信息:{}",access_token);
		JSONObject json =JSONObject.parseObject(access_token);
		access_token = json.getString("access_token");
		cache.setCACHE_VALUE(access_token);
		cache.setEXPIRE_TIME(new Date().getTime()+EXPIRE_TIME);
		map.put("access_token", cache);
//		log.info("access_token返回值：{}",JsonUtils.toJson(cache));
		return cache;
	}
}
